<template>
  <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"
        @refresh-change="handleRefreshChange"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @search-change="handleSearchChange"
      >
        <!-- <template slot="search">
          <br />
          <div class="el-form-item" v-if="orderType ===1">
            <div class="el-form-item__label">供应商12</div>
            <div class="el-form-item__content">
              <el-select
                v-model="tableQueryParam2.supplierId"
                filterable
                clearable
                size="small"
                placeholder="供应商"
              >
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.supplierName"
                >{{item.supplierName}}</el-option>
              </el-select>
            </div>
          </div>
        </template> -->

        <template slot="expand" slot-scope="scope">
          <div>
            <div v-for="(item,itemIndex) in scope.row.itemList" :key="itemIndex" class="order">
              <div class="flex">
                <img :src="item.skuImg" alt class="order__img" />
                <div>
                  <div class="order__title">
                    {{item.title}}
                    <span style="color:#999" v-if="item.orderItemNo">({{item.orderItemNo}})</span>
                  </div>
                  <div class="flex">
                    <div>
                      <div class="order__rules">{{item.skuProps|skuPropsFilter}}</div>
                      <div class="order__price">¥{{item.salePrice}} x {{item.goodsNum}}</div>
                      <div
                        class="order__supplier"
                        v-if="item.expressCompany"
                      >物流公司：{{item.expressCompany}}</div>
                      <div class="order__supplier" v-if="item.expressNo">快递订单号：{{item.expressNo}}</div>
                      <div
                        class="order__supplier"
                        v-if="item.supplierName"
                      >供应商：{{item.supplierName}}</div>
                    </div>
                    <div class="order__info">
                      <div
                        class="order__status"
                      >{{item.refundApplyProcessStatus | refundApplyProcessStatusFilter}}</div>
                      <div class="order__btns">
                        <!-- // 退款申请处理状态:1(买家申请退款)2(商家拒绝退款)3(商家待确认收货)4(待退款)5(已退款) -->
                        <el-button
                          @click="handleAggreeRefund(item,scope.row)"
                          size="mini"
                          type="primary"
                          v-if="item.refundApplyProcessStatus==1"
                        >同意退款</el-button>
                        <el-button
                          @click="handleRejectRefund(item,scope.row)"
                          size="mini"
                          type="warning"
                          v-if="item.refundApplyProcessStatus==1"
                        >拒绝退款</el-button>
                        <el-button
                          @click="handleRefundReceiveGoods(item,scope.row)"
                          size="mini"
                          type="warning"
                          v-if="item.refundApplyProcessStatus==3"
                        >确认收货</el-button>
                        <!-- <el-button @click="handleSureRefund(item,scope.row)" size="mini" type="danger" v-if="item.refundApplyProcessStatus==4">
                                  确认退款
                        </el-button>-->
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>

        <template slot="menu" scope="scope">
          <div>
            <el-button
              type="text"
              @click.stop="handleSendOrder(scope.row)"
              icon="el-icon-edit"
              size="mini"
              v-if="scope.row.orderStatus == 5"
              v-perm="'/admin/order/send_goods'"
            >发货</el-button>
          </div>
        </template>

        <template slot="menuLeft">
          <el-button
            type="primary"
            @click="handleExport"
            :loading="downloadLoading"
            icon="el-icon-download"
            v-perm="'/admin/order/export_wait_ship'"
            size="small"
          >导出</el-button>
          <!-- <el-button
            type="primary"
            @click="handleWaitSentExport"
            :loading="sendOrderDownloadLoading"
            icon="el-icon-download"
            v-perm="'/admin/order/export_wait_ship'"
            size="small"
          >导出发货订单</el-button> -->

          <!-- <el-button
            class="filter-item"
            type="primary"
            v-waves
            icon="el-icon-document"
            size="small"
            @click="downloadFile()"
          >下载批量发货模板</el-button> -->

          <!-- <el-upload
            accept
            :on-change="onchangeuploadfile"
            :before-upload="beforeuploadexcel"
            class="upload-demo"
            :headers="getHeaders()"
            name="file"
            :action="'/admin/order/import_send_goods'"
            :limit="1"
            :show-file-list="false"
            :on-success="onsuccessimport"
          >
            <el-button
              class="filter-item"
              type="primary"
              v-waves
              icon="el-icon-document"
              size="small"
            >批量发货</el-button>
          </el-upload> -->
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog :visible.sync="sendOrderDialogShowed" title="发货" width="600px">
      <div style="padding:0 30px">
        <el-form
          :disabled="isSubmiting"
          :model="sendOrderFormData"
          :rules="sendOrderFormRules"
          label-position="left"
          label-width="120px"
          ref="form1"
        >
          <el-form-item prop="expressCompanyCode" label="快递公司">
            <!-- <el-input v-model="sendOrderFormData.expressCompany" placeholder="请输入快递公司"></el-input> -->
            <el-select filterable v-model="sendOrderFormData.expressCompanyCode">
              <el-option
                :label="item.companyName"
                v-for="(item,itemIndex) in expressCompanies"
                :key="itemIndex"
                :value="item.companyCode"
              >{{item.companyName}}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="expressNo" label="快递单号">
            <el-input v-model="sendOrderFormData.expressNo" placeholder="请填写快递单号"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="sendOrderDialogShowed = false">取消</el-button>
        <el-button :loading="isSubmiting" type="primary" @click="submitFormAction">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="isImportingExcel"
      width="400px"
      :modal="false"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <div
        v-loading="isImportingExcel"
        element-loading-text="正在导入，请等待"
        element-loading-spinner="el-icon-loading"
      >正在导入</div>
    </el-dialog>
  </div>
</template>
  <script>
import { validatenull } from "@/util/validate";
import { filterForm } from "@/util/util";
// import { DIC } from "@/const/dic";
import { getLabelFromDicV2 } from "@/const/dic";
import { nowDate } from "../../util/date";
import * as apiObj from "../../api/orderInfo";
import * as supplierInfoObj from "../../api/supplierInfo";
import { orderInfoTableOption } from "@/const/orderInfo/orderInfoTableOption.js";

export default {
  data() {
    return {
      sendOrderFormData: {
        expressNo: "",
        expressCompany: "",
        expressCompanyCode: "",
        orderNo: "",
      },
      supplierList: [],
      isImportingExcel: false,
      expressCompanies: [],
      sendOrderFormRules: {
        expressCompanyCode: [
          {
            required: true,
            message: "请选择快递公司",
          },
        ],
        expressNo: [
          {
            required: true,
            message: "请填写快递单号",
          },
        ],
      },
      isSubmiting: false,
      bachDeleting: false,
      tableOption: {}, //表格设置属性
      tableData: [], //表格的数据
      downloadLoading: false,
      sendOrderDownloadLoading: false,
      sendOrderDialogShowed: false,
      tableLoading: false,
      tableQueryParam: {
        orderType: 1,
      },
      tableQueryParam2: {
        supplierId: "",
      },
      page: {
        total: 0, //总页数
        currentPage: 1, //当前页数
        pageSize: 10, //每页显示多少条
      },
    };
  },
  props: {
    orderType: {
      type: Number,
      default: 1,
    },
  },
  filters: {
    refundApplyProcessStatusFilter(v) {
      if (v) {
        return [
          "买家申请退款",
          "商家拒绝退款",
          "商家待确认收货",
          "待退款",
          "已退款",
        ][v - 1];
      }
      return "";
    },
    skuPropsFilter(v) {
      try {
        v = JSON.parse(v);
        return Object.keys(v)
          .map((key) => {
            return key + ": " + v[key];
          })
          .join(";");
      } catch (e) {
        console.error(e);
      }
      return "";
    },
  },
  created() {
    //初始化数据格式
    /** if(this.orderType != 2) {
        // orderInfoTableOption.column.filter(el=>el.prop == 'userMobile' || el.prop == 'realName' || el.prop == 'videoChannelNo').forEach(el=>el.hide = true);
        // orderInfoTableOption.column.filter(el=>el.prop == 'videoChannelNo' || el.prop == 'userMobile').forEach(el=>el.search = false);
        // orderInfoTableOption.column.filter(el=>el.prop == 'receiverMobile').forEach(el=>el.search = true);
      } else {
        // orderInfoTableOption.column.filter(el=>el.prop == 'userMobile' || el.prop == 'realName' || el.prop == 'videoChannelNo').forEach(el=>el.hide = false);
        // orderInfoTableOption.column.filter(el=>el.prop == 'videoChannelNo' || el.prop == 'userMobile').forEach(el=>el.search = true);
         // orderInfoTableOption.column.filter(el=>el.prop == 'receiverMobile').forEach(el=>el.search = false);
      }
      **/
    this.tableOption = orderInfoTableOption;
    this.handleList();
    this.loadExpressCompanies();
    this.loadSupplierList();
  },
  methods: {
    loadSupplierList() {
      supplierInfoObj.listAll().then((data) => {
        this.supplierList = data || [];
      });
    },
    downloadFile() {
      let url = "/excels/import-template.xls";
      this.openWin(url);
    },
    beforeuploadexcel(file) {},
    onsuccessimport(res, file, list) {
      list.length = 0;
      setTimeout((_) => {
        this.$nextTick((_) => {
          this.isImportingExcel = false;
        });
      }, 300);
      if (res.errcode == 0) {
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
          duration: 2000,
        });
        this.handleList();
      } else {
        this.$message({
          type: "warning",
          message: res.msg || "导入失败!",
        });
      }
    },
    onchangeuploadfile(file) {
      this.isImportingExcel = true;
    },
    handleAggreeRefund(row, order) {
      this.confirm("确定同意退款吗").then(() => {
        apiObj.aggreeRefund({ itemId: row.id, processStatus: 1 }).then(() => {
          this.success();
          this.handleList();
        });
      });
    },
    handleRejectRefund(row, order) {
      this.confirm("确定拒绝退款吗").then(() => {
        apiObj.aggreeRefund({ itemId: row.id, processStatus: 0 }).then(() => {
          this.success();
          this.handleList();
        });
      });
    },
    handleRefundReceiveGoods(row, order) {
      this.confirm("确定收货了吗").then(() => {
        apiObj.receiveRefundGoods({ itemId: row.id }).then(() => {
          this.success();
          this.handleList();
        });
      });
    },
    handleSureRefund(row, order) {
      this.confirm("确认退款了吗").then(() => {
        apiObj.sureRefund({ itemId: row.id, processStatus: 1 }).then(() => {
          this.success();
          this.handleList();
        });
      });
    },
    filterExpressCompany(v) {
      v = v.trim();
      if (!v) {
        this.expressCompanies = this.expressCompaniesCopy;
        return;
      }
      this.expressCompanies = this.expressCompaniesCopy.filter((el) => {
        if (el.companyName.includes(v) || el.companyCode.includes(v)) {
          return true;
        }
        return false;
      });
    },
    loadExpressCompanies() {
      this.$service.express.listCompany().then((data) => {
        this.expressCompanies = data || [];
        this.expressCompaniesCopy = Object.assign(this.expressCompanies);
      });
    },
    handleSendOrder(row) {
      this.currentRow = row;
      this.sendOrderDialogShowed = true;
    },
    submitFormAction() {
      this.$refs.form1.validate((valid) => {
        if (valid) {
          this.isSubmiting = true;
          apiObj
            .sendGoods({
              orderNo: this.currentRow.orderNo,
              // expressCompany:"沽沽快递",
              expressCompany: this.expressCompanies.find(
                (el) =>
                  el.companyCode == this.sendOrderFormData.expressCompanyCode
              ).companyName,
              expressCompanyCode: this.sendOrderFormData.expressCompanyCode,
              expressNo: this.sendOrderFormData.expressNo.trim(),
            })
            .then(() => {
              this.sendOrderDialogShowed = false;
              this.success();
              this.handleList();
            })
            .finally(() => {
              this.isSubmiting = false;
            });
        }
      });
    },
    handleCurrentChange(page) {
      this.page.currentPage = page;
      this.handleList();
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.handleList();
    },

    handleSelectionChange(args) {
      this.currentSelectedRowIds = args.map((el) => el.id);
    },
    hasChanged(params1, params2) {
      return Object.keys(params1).some((key) => params2[key] != params1[key]);
    },
    hasChanged(params1, params2) {
      return Object.keys(params1).some((key) => params2[key] != params1[key]);
    },
    handleSearchChange(params) {
      if (this.hasChanged(params, this.tableQueryParam)) {
        this.page.currentPage = 1;
      }
      if (this.hasChanged(params, this.tableQueryParam)) {
        this.page.currentPage = 1;
      }
      this.tableQueryParam = params;
      this.handleList();
    },

    handleRefreshChange() {
      this.handleList();
    },
    /**
     * @title 获取数据
     * @detail 赋值为tableData表格即可
     *
     **/
    handleList() {
      this.tableLoading = true;
      apiObj
        .list({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam,
          ...this.tableQueryParam2,
          orderType: this.orderType,
        })
        .then((data) => {
          this.tableData = data.data || data.dataList || [];
          this.page.total = data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    handleWaitSentExport() {
      this.sendOrderDownloadLoading = true;
      apiObj
        .exportWaitShip({
          pageNo: 1,
          pageSize: 3000,
          ...filterForm(this.$refs.crud.searchForm),
          ...this.tableQueryParam2,
          orderType: this.orderType,
        })
        .then((res) => {
          const cc = location.pathname.split("/")[1] || "";
          if (cc) {
            this.openWin("/" + cc + res);
          } else {
            this.openWin(res);
          }
          this.sendOrderDownloadLoading = false;
        })
        .catch(() => {
          this.sendOrderDownloadLoading = false;
        });
    },
    // handleExport() {
    //   this.downloadLoading = true;
    //   apiObj.list({
    //     pageNo: 1,
    //     pageSize: 3000,
    //     ...filterForm(this.$refs.crud.searchForm),
    //     ...this.tableQueryParam2,
    //     orderType:this.orderType
    //   }).then(res => {
    //     import("@/vendor/Export2Excel").then(excel => {
    //       const tHeader = ["状态","商品名称","供应商","商品规格","商品价格","商品数量","订单金额","订单编号","买家备注","支付渠道","支付时间","收货人姓名","收件人手机号码","收件人省份","收件人城市","收件人县区","收件人详细地址","快递运单号","快递物流公司","发货时间","确认收货时间","创建时间","修改时间"];
    //       const filterVal = ["itemStatus","title","supplierName","skuProps","salePrice","goodsNum","goodsAmount","orderItemNo","buyerRemark","payChannel","payTime","receiverName","receiverMobile","receiverProvince","receiverCity","receiverArea","receiverAddress","expressNo","expressCompany","sendTime","receiveTime","createTime","modifyTime"];
    //       if(this.orderType == 2) {
    //         tHeader.unshift("直播间编号");
    //         tHeader.unshift('主播姓名');
    //         tHeader.unshift('主播手机号');
    //         filterVal.unshift('videoChannelNo');
    //         filterVal.unshift('realName');
    //         filterVal.unshift('userMobile');
    //       }
    //       const dataList = res.data || res.dataList;
    //       const exportData = [];
    //       if(dataList){
    //         dataList.forEach(el=>{
    //            if(el.itemList){
    //              el.itemList.forEach(i=>{
    //                const newItem = {...el};
    //                newItem.goodsAmount = i.salePrice * i.goodsNum;
    //                delete newItem.itemList;
    //                 Object.keys(i).forEach(key=>{
    //                   if(i[key]!==null) {
    //                     newItem[key] = i[key];
    //                   }
    //                 });
    //                 exportData.push(newItem);
    //              });
    //            }
    //         });
    //       }
    //       const data = this.formatJson(filterVal, exportData);
    //       excel.export_json_to_excel({
    //         header: tHeader,
    //         data,
    //         filename: (this.orderType==1?'平台':'主播')  + "订单" + nowDate()
    //       });
    //       this.downloadLoading = false;
    //     });
    //   });
    // },
    handleExport() {
      this.downloadLoading = true;
      let func = apiObj.exportPlatform;
      if (this.orderType == 2) {
        func = apiObj.exportAnchor;
      }
      func({
        pageNo: 1,
        pageSize: 3000,
        ...filterForm(this.$refs.crud.searchForm),
        ...this.tableQueryParam2,
        orderType: this.orderType,
      })
        .then((res) => {
          const cc = location.pathname.split("/")[1] || "";
          if (cc) {
            this.openWin("/" + cc + res);
          } else {
            this.openWin(res);
          }
          this.downloadLoading = false;
        })
        .catch(() => {
          this.downloadLoading = false;
        });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return getLabelFromDicV2(
            this.$refs.crud.DIC,
            j == "itemStatus" ? "orderStatus" : j,
            v[j]
          );
        })
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.order {
  display: flex;
  padding: 10px 0 10px 60px;
  align-items: center;
  .order__title {
    font-size: 14px;
    font-weight: bold;
  }
  .order__price {
    color: red;
  }
  .order__supplier {
    color: #999;
  }
  .order__rules {
    color: blue;
    font-size: 12px;
  }
  .order__img {
    width: 70px;
    height: 70px;
    display: block;
    margin-right: 10px;
  }
}
.order__info {
  padding-left: 20px;
  .order__status {
    font-size: 12px;
  }
}

.upload-demo {
  display: inline-block;
  margin-left: 0px;
}
</style>
